#pragma once
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include "../comm/Util.hpp"
#include "../comm/Log.hpp"
namespace ns_runner
{
    using namespace ns_log;
    class Runner
    {
    public:
        Runner()
        {
        }
        ~Runner()
        {
        }

    public:
        // 添加资源限制接口
        //_cpu用于限制程序运行时间
        //_size用于限制程序大小，一般都是KB结尾
        static void SetSourceLimit(int cpu_limit, int mem_limit)
        {
            // 限制cpu
            struct rlimit r_cpu;
            r_cpu.rlim_cur = cpu_limit;
            r_cpu.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &r_cpu);

            // 限制程序大小
            struct rlimit r_size;
            r_size.rlim_cur = mem_limit * 1024;
            r_size.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &r_size);
        }
        static int Run(const std::string &file_name, int cpu_limit, int mem_limit)
        {

            // 将标准输入、标准输出、标准错误重定向到对应文件
            std::string _stdin = PathUtil::StdIn(file_name);
            std::string _stdout = PathUtil::StdOut(file_name);
            std::string _stderr = PathUtil::StdErr(file_name);
            ::umask(0);
            int _stdin_fd = ::open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = ::open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = ::open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);
            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(ERROR) << "运行时打开标准文件失败" << "\n";
                return -1;
            }
            // run模块，运行编译之后的.exe文件
            std::string _execute = PathUtil::Exe(file_name);
            pid_t pid = ::fork();
            if (pid < 0)
            {
                // 创建子进程失败
                LOG(ERROR) << "运行时子进程创建失败！" << "\n";
                ::close(_stdin_fd);
                ::close(_stdout_fd);
                ::close(_stderr_fd);
                return -2;
            }
            else if (pid == 0)
            {
                // 子进程
                // 程序替换execl
                ::dup2(_stdin_fd, 0);
                ::dup2(_stdout_fd, 1);
                ::dup2(_stderr_fd, 2);
                SetSourceLimit(cpu_limit, mem_limit);
                ::execl(_execute.c_str(), _execute.c_str(), nullptr);
                LOG(ERROR) << "程序运行失败，可能是不存在该可执行文件" << "\n";
                exit(1);
            }
            else
            {
                // 父进程
                ::close(_stdin_fd);
                ::close(_stdout_fd);
                ::close(_stderr_fd);
                int status = 0; // 获取子进程的退出状态
                ::waitpid(pid, &status, 0);
                LOG(INFO) << "运行完毕,info:" << (status & 0x7F) << "\n";
                return status & 0x7F;
            }
        }
    };
}